package com.morty.config.filter;

import com.morty.config.utils.ThreadContextHolder;
import com.morty.config.utils.TraceUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 首先创建拦截器，加入拦截列表中，在请求到达时生成traceId。
 */
public class LogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //traceId初始化
        initTraceId(request);
        return true;
    }

    /**
     * traceId初始化
     */
    private void initTraceId(HttpServletRequest request) {
        //尝试获取http请求中的traceId
        String traceId = TraceUtil.getTrace();

        //如果当前traceId为空或者为默认traceId，则生成新的traceId
        if (StringUtils.isBlank(traceId) || TraceUtil.defaultTraceId(traceId)){
            traceId = TraceUtil.genTraceId();
        }

        //设置traceId
        TraceUtil.setTraceId(traceId);
        ThreadContextHolder.putTraceId(traceId);
    }
}